<template>
	<view class="y-flex y-flex-1 position-relative">
		<find-short-player ref="sp" :sliderEnd="sliderEnd"
		@ready="refresh"
		@pulldown="handlePulldown"
		@pullup="handlePullup"
		@change="changeCurrent"
		@more="showModal"
		@list="showItems"></find-short-player>
		<com-popup position="absolute" :visible.sync="modalShow" direction="bottom" @hide="handleModalHide">
			<view class="y-flex" :style="{'background-color': pageStyle.background, 'height': modalHeight + 'px'}">
				<module-list
				ref="list"
				:params="modalParams"
				:component="components"
				:cell="cell"
				:comment="comments"
				:bounce="pageStyle.enableBounce"
				:back-top-show="pageStyle.enableBackTop"
				:refreshImage="pageStyle.pulldownRefreshImage"
				:pulldownable="pageStyle.enablePulldown == 1"
				:loadmoreable="pageStyle.enableLoadmore == 1"
				:loadingColor="pageStyle.loadingColor"
				:backTopImage="pageStyle.backTopImage"
				@pulldown="handleModalPulldown">
					<template #top v-if="detail && detail.title">
						<cell v-if="detail && detail.title">
							<find-detail ref="detail"
							:data="detail"
							:options="detailOptions"
							:bg-color="componentStyle['background-color']"
							:style="componentStyle"></find-detail>
						</cell>
					</template>
				</module-list>
			</view>
		</com-popup>
		<view class="position-absolute" :style="{
			top: tabsTop + 'px',
			left: tabsLeft,
			right: tabsRight
		}" v-if="subsection.length > 1">
			<com-tabs
			bg-color="rgba(0,0,0,0)"
			border-color="rgba(0,0,0,0)"
			text-color="#eee"
			selected-color="#fff"
			text-size="30"
			line-size="4"
			gap="16"
			height="60"
			:column="subsectionColumn"
			:current="subsectionSelectedIndex"
			:data="subsection"
			@change="handleTabsChange"></com-tabs>
		</view>
		<com-popup position="absolute" :visible.sync="itemsShow" direction="bottom" @hide="handleItemsHide">
			<view class="y-flex" :style="{'height': modalHeight + 'px', 'background-color': skinColor.color_bg_1}">
				<com-tabs
				:current="subsectionSelectedIndex"
				:column="subsectionColumn"
				:bg-color="subsectionBackgroundColor"
				:text-color="skinColor.color_1"
				:border-color="skinColor.color_gap_1"
				:selected-color="subsectionSelectedColor"
				:enable-swiper="false"
				:data="subsection"
				v-if="subsection.length > 1"
				@change="handleTabsChange"></com-tabs>
				<com-list ref="items" class="y-flex-1" pulldownable @pulldown="handlePulldown" @loadmore="handlePullup">
					<cell v-for="(grid, i) in Math.ceil(items.length / itemCellColumn)" ref="item">
						<view class="y-flex pt-30 pb-30 border-bottom-1 border-bottom-style-dashed" :style="cellRealStyle">
							<com-grid :data="items.slice(i * itemCellColumn, (i + 1) * itemCellColumn)"
							:column="itemCellColumn"
							:count="itemCellColumn"
							:gap="20">
								<template v-slot="{item, index}">
									<find-img-cell
									:options="itemCellStyle"
									:item="item"
									@click="slideTo((i * itemCellColumn) + index)"></find-img-cell>
									<view class="position-absolute-cover bg-dark-mask y-flex y-align-center y-justify-center" v-if="current == (i * itemCellColumn) + index">
										<text class="fs-28 fr-fff">正在播放中</text>
									</view>
								</template>
							</com-grid>
						</view>
					</cell>
					<cell>
						<com-loadmore class="mt-30 mb-30" :color="pageStyle.loadingColor" :state="itemLoadmore" @loadmore="handlePullup"></com-loadmore>
					</cell>
				</com-list>
			</view>
		</com-popup>
		<view class="position-absolute-cover y-flex y-align-center y-justify-center" v-if="loading">
			<com-loading color="#fff" size="50"></com-loading>
		</view>
	</view>
</template>

<script>
	import { pixelunit, hexToRgba, isContained } from '@/assets/js/util.js'
	import ModuleList from './components/ModuleList.vue'
	import FindDetail from './components/FindModule/FindDetail.vue'
	import FindImgCell from './components/FindCell/ImgCell.vue'
	import FindShortPlayer from './components/ShortPlayer.vue'
	export default {
		inject: ['getPageStyle', 'getComponentStyle', 'getCellStyle', 'getPage', 'getQuery', 'getSkinColor', 'getNavbarHeight', 'getWindowTop', 'getInnerHeight', 'getTabbarIndex', 'getWindowWidth', 'sharePoster'],
		components: {ModuleList, FindDetail, FindImgCell, FindShortPlayer},
		computed: {
			sliderEnd () {
				return this.$store.getters['setting/GET_VIDEO_SLIDER_ENDED']
			},
			//是否开启调试模式
			debug () {
				return this.$store.getters['setting/GET_DEBUG']
			},
			page () {
				return this.getPage()
			},
			skinColor () {
				return this.getSkinColor()
			},
			pageStyle () {
				return this.getPageStyle()
			},
			query () {
				return this.getQuery()
			},
			modalHeight () {
				return this.getInnerHeight() - (this.pageStyle?.enableNavigationTransparent ? this.getNavbarHeight() : 0)
			},
			itemHeight () {
				return this.modalHeight * (2/3)
			},
			windowWidth () {
				return this.getWindowWidth()
			},
			componentStyle () {
				const style = this.getComponentStyle()
				return {
					'margin-top': pixelunit(style.marginTop),
					'margin-bottom': pixelunit(style.marginBottom),
					'margin-left': pixelunit(style.marginLeft),
					'margin-right': pixelunit(style.marginRight),
					'background-color': hexToRgba(style.backgroundColor, style.backgroundOpacity),
					'border-radius': pixelunit(style.borderRadius)
				}
			},
			cellRealStyle () {
				const style = this.getCellStyle()
				return {
					'margin-left': pixelunit(style.marginLeft),
					'margin-right': pixelunit(style.marginRight),
					'padding-left': pixelunit(style.paddingLeft),
					'padding-right': pixelunit(style.paddingRight),
					'background-color': hexToRgba(style.backgroundColor, style.backgroundOpacity),
					'border-color': this.skinColor.color_gap_1
				}
			},
			detailOptions () {
				return {
					enableButton: 0
				}
			},
			itemOptions () {
				return {
					title: '其它视频',
					unit: "个视频"
				}
			},
			network () {
				return this.$store.getters['network/GET']
			},
			cell () {
				return this.page?.cell || {}
			},
			comments () {
				return this.page?.comments || {}
			},
			components () {
				return this.page?.components || []
			},
			//选项栏栏数
			subsectionColumn () {
				return this.pageStyle.subsectionColumn || 'auto'
			},
			//选项栏背景色
			subsectionBackgroundColor () {
				return this.pageStyle.subsectionBackgroundColor || this.skinColor.color_bg_1
			},
			//选项栏选中高亮色
			subsectionSelectedColor () {
				return this.pageStyle.subsectionSelectedColor || this.pageStyle.themeColor || this.skinColor.color_blue
			},
			tabsTop () {
				return this.pageStyle?.enableNavigationTransparent ? this.getWindowTop() + uni.upx2px(24) : 0
			},
			tabsRight () {
				let right = this.pageStyle?.enableNavigationTransparent ? 280 : 0
				right = this.debug ? right : right - 70
				return right + 'rpx'
			},
			tabsLeft () {
				return this.getTabbarIndex() > -1 ? '210rpx' : '20rpx'
			},
			detail () {
				return this.items[this.current] || null
			},
			modalParams () {
				return Object.assign({}, this.query, this.detail)
			}
		},
		data () {
			return {
				loading: false,//显示加载图标
				subsection: [],//选项栏数据
				subsectionSelectedIndex: 0,//选项栏选中索引
				modalShow: false,//更多模块展示
				current: 0,//当前项
				items: [],//items列表
				itemPage: 1,//item页数
				itemLoadmore: '',//item加载状态
				itemNextUrl: '',//item下一页
				itemCellColumn: 2,
				itemCellStyle: {
					cellImageHeight: 500
				},
				itemsShow: false
			}
		},
		methods: {
			refresh () {
				this.loading = true
				this.getSubsection()
			},
			onBackPress () {
				if ( this.itemsShow ) {
					this.itemsShow = false
					return true
				}
				if ( this.modalShow ) {
					this.modalShow = false
					return true
				}
				return false
			},
			play () {
				this.$refs.sp.play()
			},
			pause () {
				this.$refs.sp.pause()
			},
			//播放子视频
			slideTo (index) {
				this.itemsShow = false
				this.$refs.sp.slideTo(index)
			},
			changeCurrent (current) {
				this.current = current
				const item = this.items[current], utils = []
				if ( item ) {
					item.shareUrl = item.shareUrl || item.src
					item.uniqueId = item.id || item.shareUrl
					if ( item.shareUrl ) {
						utils.push({
							label: '分享资源',
							icon: 'forward',
							func: () => {
								this.sharePoster(item)
							}
						})
					}
				}
				this.$emit('utils', utils)
			},
			async getSubsection () {
				this.subsection = await this.handleGetSubsection()//获取选项栏数据
				this.subsectionSelectedIndex = this.subsection.findIndex(s => s.value == this.query.selected)//是否携带tabs选项栏指定位置
				if ( this.subsectionSelectedIndex == -1 ) this.subsectionSelectedIndex = 0
				this.current = this.query.current || 0//是否携带current指定位置
				this.handlePulldown()
			},
			handleTabsChange (e) {
				if ( this.changeTimer ) {
					clearTimeout(this.changeTimer)
					this.changeTimer = null
				}
				this.subsectionSelectedIndex = e.current
				this.$nextTick(function () {
					this.changeTimer = setTimeout(() => {
						this.current = 0//重置current
						this.handlePulldown()
					}, 300)
				})
			},
			async handlePulldown (callback) {
				try{
					this.loading = true
					this.itemPage = 1
					this.itemLoadmore = ''
					this.itemNextUrl = ''
					this.items = await this.handleGetItems()
					this.$refs.sp.init(this.items)
					this.$nextTick(() => {
						if ( this.current > 0 ) {
							this.$refs.sp.slideTo(this.current)//滑动到指定项
						} else {
							this.changeCurrent(this.current)
						}
					})
					callback && callback('success')
				}catch(e){
					this.$refs.sp.setPulldown('fail')
					callback && callback('fail')
				}
				this.loading = false
				this.$emit('loaded', true)
			},
			async handlePullup(callback) {
				try{
					if ( ['loading', 'end'].includes(this.itemLoadmore) ) return
					this.itemPage++
					this.itemLoadmore = 'loading'
					const list = await this.handleGetItems()
					const isCon = isContained(this.items, list)
					if ( isCon || list.length == 0 ) {
						this.$refs.sp.setPullup('end')
						this.itemLoadmore = 'end'
					} else {
						this.items = this.items.concat(list)
						this.$refs.sp.insert(list)
						this.$refs.items.resetLoadmore()
						this.itemLoadmore = ''
						
					}
				}catch(e){
					this.$refs.sp.setPullup('fail')
					this.$refs.items.resetLoadmore()
					this.itemLoadmore = 'fail'
				}
			},
			showItems () {
				this.pause()
				this.$emit('scroll', 200)
				this.itemsShow = true
				this.$nextTick(() => {
					setTimeout(() => {
						//滚动到索引位置
						const index = parseInt(this.current / this.itemCellColumn)
						uni.requireNativePlugin('dom').scrollToElement(this.$refs.item[index], {
							animated: false
						})
					}, 200)
				})
			},
			handleItemsHide () {
				this.play()
				this.modalShow = false
				this.$emit('scroll', 0)
			},
			showModal () {
				this.pause()
				this.modalShow = true
				this.$emit('scroll', 200)
				this.$nextTick(function () {
					this.handleModalPulldown()
				})
			},
			handleModalHide () {
				this.play()
				this.modalShow = false
				this.$emit('scroll', 0)
			},
			async handleModalPulldown (callback) {
				this.$refs.list && this.$refs.list.initModule(callback, callback ? true : false)
			},
			async handleGetSubsection () {
				const subsection = this.page?.subsection || {}
				const staticData = subsection.staticData ? await this.network.staticDataHandle(subsection.staticData, this.query) : []
				const dynamicData = subsection.dynamicData
				const request = subsection.request
				let list = []
				if ( dynamicData && request ) {
					const newRequest = await this.network.requestHandle(request, this.query)
					const response = await this.network.$request(newRequest)
					if ( response.data ) list = await this.network.$list(dynamicData, response.data, response.taskId)
				}
				return staticData.concat(list)
			},
			async handleGetItems () {
				const items = this.page?.items || {}
				const params = Object.assign({}, this.query, {page: this.itemPage, list: this.items, selected: this.subsection[this.subsectionSelectedIndex]?.value})
				const staticData = items.staticData ? await this.network.staticDataHandle(items.staticData, params) : []
				const dynamicData = items.dynamicData
				const request = items.request
				let list = []
				if ( dynamicData && request ) {
					const newRequest = await this.network.requestHandle(request, params)
					const response = await this.network.$request(this.itemNextUrl ? Object.assign({}, newRequest, {url: this.itemNextUrl}) : newRequest)
					this.itemNextUrl = newRequest.nextUrl ? await this.network.$text(newRequest.nextUrl, response.data, response.taskId) : ''
					if ( response.data ) list = await this.network.$list(dynamicData, response.data, response.taskId)
				}
				return staticData.concat(list)
			}
		}
	}
</script>

<style>
</style>
